<template>
    <div class="myOrder">
        <ul class="tabs clearfix">
            <a class="tab" :class="{on: num == 0}" @click="clicktab(0)">所有订单</a>
            <a class="tab" :class="{on: num == 1}" @click="clicktab(1)">待支付订单</a>
            <a class="tab" :class="{on: num == 2}" @click="clicktab(2)">已完成订单</a>
        </ul>
        <div class="notdata" v-if="notdata">
            <i class="iconfont">&#xe6be;</i>暂无订单
        </div>
        <div class="person_info" v-if="!notdata">
            <div class="order_content" v-for="(item, index) in pageObj.order" :key="index">

                <div class="order_title clearfix">
                    <span class="order_num">订单号：{{item.orderNo}}</span>
                    <span class="time">下单时间：{{item.gmtCreate}}</span>
                </div>
                <div class="order_body clearfix">
                    <div class="body_left clearfix">
                        <div class="img_box fl" v-if="item.courseCover">
                            <img :src="item.courseCover" alt="">
                        </div>
                        <p class="fl">
                            {{item.courseTitle}}
                        </p>
                    </div>
                    <ul class="body_right clearfix">
                        <li class="money">￥{{item.totalFee}}</li>
                        <li v-if="item.payType == 0">微信支付</li>
                        <li v-if="item.payType == 1">支付宝支付</li>
                        <li class="alipay" v-if="item.status == 0">等待支付</li>
                        <li class="alipay" v-if="item.status == 1">已支付</li>
                        <li v-if="item.status == 1">
                            <router-link :to="{name: 'DetailId', params: {id: item.courseId}}" class="go_btn">进入学习</router-link>
                        </li>
                        <li v-else-if="item.status == 0 ">
<!--                            <a class="go_btn go_pay" v-if="item.status == 1" @click="submitAlipay(item.courseId)">继续支付</a>-->
                            <a class="go_btn go_pay" @click="submit(item.courseId,item.payType,item.orderNo)">继续支付</a>
                            <a @click="quxiao(item.id)" class="cancel" style="cursor: pointer">取消支付</a>
                        </li>
                    </ul>
                </div>
            </div>
            <!--                            微信支付-->
            <el-dialog
                    title="收银台"
                    :visible.sync="dialogVisible"
                    width="30%"
            >
                <div style="text-align: center">
                    <p>微信支付 {{payResult.total_fee}}元</p>
                    <div style="border: 1px solid #f3f3f3;width: 220px;padding: 10px;margin: 0px auto">
                        <vue-qr
                                :text="payResult.code_url"
                                :margin="0"
                                colorDark="red"
                                :logoSrc="require('/src/assets/img/wx.jpg')"
                                colorLight="#fff"
                                :size="200">

                        </vue-qr>
                    </div>
                </div>
                <el-divider></el-divider>
                <div style="font-size: 13px">
                    提示:<br>
                    支付成功前请勿手动关闭页面<br>
                    二维码两小时内有效,请及时扫码支付<br>
                </div>

            </el-dialog>
            <d-page v-if="pageObj.totalPage > 1 && !notdata" :page="pageObj" @btnClick="getPage"></d-page>
        </div>
    </div>

</template>

<script>
    import YSide from '@/components/account/Side'
    import DPage from '@/components/Page'
    import vueQr from 'vue-qr'
    export default {
        name: "MyOrder",

        data () {
            return {
                num: 0,
                showPay: false,
                payData: null,
                notdata: false,
                zhuangtai:"",
                //用户id
                HuiYuanId: window.sessionStorage.getItem("memberId"),
                timer1: '',
                dialogVisible: false, //弹出框
                //得到响应的结果
                payResult: {
                    code_url: "", //二维码的地址
                    out_trade_no: "", //订单号
                    total_fee: 0.00, //支付的金额
                    course_id: "", //课程id
                    // logoSrc: "/src/assets/img/wx.jpg" //微信二维码中间小logo
                },
                pageObj: {
                    //当前页面--》page
                    pageCurrent: '1',
                    //每页条数--》limit
                    pageSize: '5',
                    //总条数
                    totalCount: '',
                    //total的页数（有几页）【totalCount/pageSize】
                    totalPage: '',
                    order:[
                        {
                            id:'',
                            orderNo:'',
                            courseId:'',
                            gmtCreate:'',
                            courseCover:'',
                            courseTitle:'',
                            totalFee:'',
                            payType:'',
                            status:'',
                        },
                    ]
                },
                order_no:this.$route.query.out_trade_no,
            }
        },
        methods: {
            queryPayStatus(orderNo) {
                //继续支付
                var that = this;
                console.log(this.payResult.out_trade_no);
                this.$http.post("/order/pay/getPayStatus/" + orderNo).then(r => {
                    if (r.data.code === 2000) {
                        //如果支付成功，清除定时器
                        clearInterval(that.timer1)
                        that.timer1 = null;
                        that.$message({
                            type: 'success',
                            message: '支付成功!'
                        })
                        that.dialogVisible = false;
                        //刷新界面
                        this.$router.go(0);
                        //跳转到课程详情页面观看视频
                        // that.$router.push({path: '/DetailId/:id' + that.payResult.course_id})
                    }
                })
            },
            submitAlipay(courseId){
                const that = this;
            },
            //微信下单
            submit(courseId,payType,orderNo) {

                //设置一个定时任务，每隔3秒调用一次
                if (payType==0){
                    const that = this;
                    this.$http.post("/order/pay/createWeiXin/" + courseId + "/" + this.HuiYuanId).then(function (resp) {
                        // alert(courseId)
                        that.dialogVisible = true;
                        if (resp.data.code === 2000) {

                            that.payResult = resp.data.data;
                            // console.log(that.payResult.total_fee);
                        } else {
                            that.$message.error("订单已经生成,尚未支付");
                        }
                    })
                    //设置一个定时任务，每隔3秒调用一次
                    this.timer1 = setInterval(() => {
                        this.queryPayStatus(orderNo)
                    }, 4000);
                    this.dialogVisible = false;
                }
                // 支付宝支付
                else{
                    var that = this;
                    // this.$http.get("/order/pay/allPay/" + courseId + "/" + this.HuiYuanId).then(function (resp) {
                    this.$http.post(`/order/pay/allPay/${courseId}/${this.HuiYuanId}`).then(function (resp) {
                        // 添加之前先删除一下，如果单页面，页面不刷新，添加进去的内容会一直保留在页面中，二次调用form表单会出错
                        const divForm = document.getElementsByTagName("div");
                        if (divForm.length) {
                            document.body.removeChild(divForm[0]);
                        }
                        const div = document.createElement("div");
                        div.innerHTML = resp.data.data; // data就是接口返回的form 表单字符串
                        document.body.appendChild(div);
                        document.forms[0].submit();
                        this.$router.go(0);

                        // that.$message.success(resp.data)
                        // 关键代码，用于处理sb支付宝返回的数据，以下代码会开一个新页面用于支付
                        // document.createElement("div").innerHTML = resp.data.data
                        // document.forms[1].setAttribute('target', '_blank')
                        // document.forms[1].submit()
                        // location.href=resp.data.data;
                        // // 添加之前先删除一下，如果单页面，页面不刷新，添加进去的内容会一直保留在页面中，二次调用form表单会出错
                        // const divForm = document.getElementsByTagName("div");
                        // if (divForm.length) {
                        //     document.body.removeChild(divForm[0]);
                        // }

                        // const div = document.createElement("div");
                        // div.innerHTML = resp.data.data; // data就是接口返回的form 表单字符串
                        // document.body.appendChild(div);
                        // document.forms[0].setAttribute("target", "_blank"); // 新开窗口跳转
                        // document.forms[0].submit();
                        // this.$router.go(0);
                        // that.ZhiFuBaoStatus=resp.data.result.emptyOfEntity;
                        // alert(that.ZhiFuBaoStatus)
                        // this.$http.post("/order/order/updateZhiFuStatus/"+this.classData.id+"/"+this.HuiYuanId).then(function (resp) {
                        // })
                        // console.log(resp.data)
                        // that.$message.error("卧槽!")
                        // that.$message.success(resp.data.data)
                        // // that.$message.success(resp.data)
                        // let divForm = document.getElementsByTagName('divform')
                        // if (divForm.length) {
                        //     document.body.removeChild(divForm[0])
                        // }
                        // const div = document.createElement('divform')
                        // div.innerHTML = resp.data // res.data就是sb支付宝返回给你的form
                        // document.body.appendChild(div)
                        // // document.forms[0].setAttribute('target', '_blank') // 加了_blank可能出问题所以我注释了
                        // document.getElementById('alipay_submit').submit()


                    })
                }

            },
            pay (item) {
                this.payData = item;
                this.showPay = true;
            },
            //头部选择的按钮
            clicktab (int) {
                this.num=int;
                this.pageObj.pageCurrent = 1;
                this.pageObj.pageSize = 5;
                this.pageObj.totalPage='',
                this.getOrderList(int);
            },

            //监听分页的触发
            getPage: function (int) {
                this.pageObj.pageCurrent=int;
                this.initOrderList();
            },

            //订单数据重载，，判断要查询所有还是查询支付或未支付订单
            getOrderList (int) {
                if (int===1){//查询待支付订单
                    this.zhuangtai=0;
                }else if (int===2){//已支付订单
                    this.zhuangtai=1;
                }else if (int===0){//查询所有
                    this.zhuangtai="";
                }
                this.initOrderList()
            },

            //获取订单信息
            initOrderList(){
                this.notdata=false;
                var mobile=window.sessionStorage.getItem("mobile")
              var that=this;
              this.$http.post(`/order/order/getAllOrder/${this.pageObj.pageCurrent}/${this.pageObj.pageSize}`,{'status':this.zhuangtai,'mobile':mobile}).then(function (resp) {
                  that.pageObj.order=resp.data.data.records;
                  that.pageObj.totalCount=resp.data.data.total;
                  if (resp.data.data.total===0){
                      that.notdata=true;
                  }
                 that.pageObj.totalPage=Math.ceil(that.pageObj.totalCount/5)
              })
            },

            //取消支付
            quxiao(id){
                this.$confirm(`确定要取消支付吗?`, {
                    confirmButtonText: '确定',
                    cancelButtonText: '取消',
                    type: 'warning'
                }).then(() => {
                    var that=this;
                    this.$http.post(`/order/order/deleteOrder/${id}`).then(function (resp) {
                        if (resp.data.code===2000){
                            that.$message.success(resp.data.msg);
                        }else {
                            that.$message.error(resp.data.msg);
                        }
                        that.pageObj.pageCurrent = 1;
                        that.initOrderList();
                    })
                }).catch(() => {
                    this.$message({
                        type: 'info',
                        message: '取消支付失败'
                    });
                })



            }

        },
        mounted () {
            this.getOrderList();
        },
        components: {
            YSide,
            DPage,
            vueQr
        }

    }
</script>

<style lang="scss" rel="stylesheet/scss" scoped>
    .person_info {
        padding: 25px;
        min-height: 400px;
    }
    .order_content {
        border-bottom: 2px solid rgba(245, 245, 245, 1);
        margin-top: 20px;
        position: relative;
        &:first-child {
            margin-top: 0;
        }
    }
    .order_title {
        line-height: 36px;
        padding-left: 20px;
        background: rgba(245, 245, 245, 1);
        font-size: 14px;
        color: #999;
        .order_type {
            margin-right: 10px;
            color: #0099FF;
        }
        .time {
            margin-left: 30px;
        }
    }
    .order_body {
        margin: 15px 0;
    }
    .body_left {
        padding: 0 20px;
        float: left;
        // position: relative;
        .img_box {
            width: 120px;
            height: 59px;
            display: inline-block;
        }
        img {
            width: 120px;
            height: 59px;
        }
        p {
            // position: absolute;
            width: 336px;
            white-space: inherit;
            margin-left: 10px;
            // left: 160px;
            font-size: 14px;
            color: #999;
        }
    }
    .body_right {
        float: right;
        li {
            float: left;
            height: 59px;
            width: 100px;
            text-align: center;
            border-left: 2px solid rgba(245, 245, 245, 1);
            font-size: 14px;
            color: #999;
            &.alipay {
                color: #0099FF;
            }
            &.money {
                color: #D51423;
            }
            .cancel {
                display: block;
                text-align: center;
                margin-top: 5px;
                color: #999;
                &:hover {
                    color: #D51423;
                }
            }
            .go_btn {
                display: block;
                width: 76px;
                height: 30px;
                margin-left: 10px;
                line-height: 30px;
                background: #fff;
                border-radius: 6px;
                font-size: 14px;
                cursor: pointer;
                color: #999;
                border: 1px solid #999;
                &.go_pay {
                    border-color: orange;
                    color: orange;
                }
                &:hover {
                    color: #D51423;
                    border-color: #D51423;
                }
            }
        }
    }
    .notdata{
        text-align: center;
        padding: 60px 0;
        font-size: 30px;
        color: #999;
        min-height: 400px;
        i{
            font-size: 30px;
            padding-right: 12px;
        }
    }
    .page {
        margin-bottom: 20px;
        margin-top: 10px;
    }
</style>
